<template>
  <div
    :ref="'player-' + info.uuid"
    :class="{'player-main':true,'active':isBarShow}"
    @click="$emit('change-selected',info)"
    @mouseover="mouseOver"
    @mouseleave="mouseLeave"
  >
    <template v-if="info.cameraInfo[treeNodeKey]">
      <!-- 标题栏 -->
      <top-bar
        ref="topBar"
        class="player-top-bar"
        :title="info.cameraInfo.name"
        :title-show="titleShow"
        @clear-player="clearPlayer"
      />
      <!-- 播放器 -->
      <play-video
        v-if="reset"
        ref="player"
        :info="info.cameraInfo"
        :object-fit="objectFit"
        :authorization="authorizationId"
        :max-reconnect-times="layoutConfig.reconnectTimes"
        :reconnect-duration="layoutConfig.reconnectDuration"
        :server="{
          stream: {
            serverIp: layoutConfig.server.stream.ip,
            serverPort: layoutConfig.server.stream.port
          },
          ws: {
            serverIp: layoutConfig.server.ws.ip,
            serverPort: layoutConfig.server.ws.port
          }
        }"
        @db-click="fullScreen"
        @play="play"
        @stop="stop"
        @message="message"
        @change-selected="$emit('change-selected', info)"
      />
      <!-- 工具栏 -->
      <bottom-bar
        v-if="layoutConfig.showToolbar"
        ref="bottomBar"
        class="player-bottom-bar"
        :title-show="titleShow"
        :is-muted="isMuted"
        :is-recording="isRecording"
        :frame="frame"
        :bitrate="bitrate"
        :disabled="toolsDisabled"
        @enter-btn="enterBottomBtn"
        @video-type-change="videoTypeChange"
      />
      <!-- 播放状态 -->
      <div v-if="statusLabel" class="label-message">
        <div v-html="statusLabel" />
        <el-button
          v-if="again"
          type="text"
          @click="$refs['player'].connectNow()"
        >
          立即重连
        </el-button>
      </div>
      <!-- 叠加信息 -->
      <template v-if="layoutConfig.showSmart && $refs['player'] && smartList.length">
        <mind-message
          v-for="(item,index) in smartList[0].list"
          :key="index"
          :message="item.message"
          :center="item.center"
          :position="item.position"
          :text-align="item.textAlign"
        />
      </template>
    </template>
  </div>
</template>

<script>
import { uuid } from 'vue-uuid'
import { defaultState } from '@/components/VideoManagement/mixins'
import { BottomBarControl } from './components/ivms/BottomBarMethods'
import PlayVideo from './components/PlayVideo'
import TopBar from './components/TopBar'
import BottomBar from './components/BottomBar'
import MindMessage from './components/MindMessage'

export default {
  name: 'PlayerMain',
  components: {
    PlayVideo,
    TopBar,
    BottomBar,
    MindMessage
  },
  mixins: [defaultState],
  props: {
    cameraId: {
      type: String,
      default: ''
    },
    info: {
      type: Object,
      default: () => {
        const _info = {
          layoutId: uuid.v1(),
          cameraInfo: {},
          replay: {},
          time: 0
        }
        _info.cameraInfo[this.treeNodeKey] = ''
        return _info
      }
    }
  },
  data() {
    return {
      objectFit: 'contain',
      statusLabel: '',
      isBarShow: false,
      control: null,
      isMuted: false,
      isRecording: false,
      frame: '',
      bitrate: '',
      titleShow: true,
      smartList: [],
      again: false,
      toolsDisabled: true,
      type: 0,
      reset: true
    }
  },
  watch: {
    cameraId(val, oldVal) {
      if (val !== oldVal) {
        this.reset = false
        this.$nextTick(() => {
          this.reset = true
        })
      }
    }
  },
  methods: {
    mouseOver() {
      this.isBarShow = true
    },
    mouseLeave() {
      this.isBarShow = this.$refs['bottomBar'] && this.$refs['bottomBar'].isShow
    },
    // 提示信息
    message(params) {
      const { type, msg } = params
      switch (type) {
        case 'ready':
          this.statusLabel = '正在连接，请稍后……'
          break
        case 'error':
          console.log(msg)
          break
        case 'reconnect':
          this.toolsDisabled = true
          const { count, time } = msg
          if (time === 0) {
            this.statusLabel = `正在连接，请稍后……`
            this.again = false
          } else {
            this.again = true
            this.statusLabel = `<p>第${count}次重连   ${time}秒后进行重连</p>`
          }
          break
        case 'disconnect':
          this.again = true
          this.toolsDisabled = true
          this.statusLabel = msg || '<p>连接被迫断开</p><p>请稍后再试或联系管理员</p>'
          break
      }
    },
    // 开始播放
    play() {
      this.statusLabel = ''
      this.again = false
      this.setBottomBar()
      this.getSmartList()
    },
    // 停止播放
    stop() {
      if (this.control) {
        this.control.destroy()
        this.control = null
        this.toolsDisabled = true
      }
    },
    // 声明设置底部工具条
    setBottomBar() {
      const player = this.$refs['player']
      if (player.pc) {
        this.control = new BottomBarControl({
          el: player.$refs['videoBox'],
          pc: player.pc,
          video: player.$refs[player.id],
          title: this.info.cameraInfo.name,
          vm: this
        })
        this.frame = ''
        this.bitrate = ''
        this.control._setNetInformationListener()
        this.control.on('setMsg', (msg) => {
          const { frame, bitrate } = msg
          this.frame = frame
          this.bitrate = bitrate
        })
        this.toolsDisabled = false
      }
    },
    // 底部按钮功能
    enterBottomBtn(e) {
      if (e.method === 'isShowTitle') {
        this.titleShow = !this.titleShow
      } else {
        this.$nextTick(() => {
          // 执行绑定方法
          if (!e.disabled && e.method) {
            try {
              this.control.eval(e.method)
            } catch (e) {
              this.$message.warning('视频未就绪，请稍后再试')
            }
          }
        })
      }
    },
    // 双击全屏
    fullScreen() {
      this.stopCarousel()
      this.enterBottomBtn({
        disabled: false,
        method: 'fullScreen'
      })
    },
    // 切换视频填充格式
    videoTypeChange(e) {
      this.$refs['player'].changeFit(e)
    },
    // 清空播放器
    clearPlayer() {
      this.$refs['player'].$destroy()
      this.stopCarousel()
      const _info = {
        layoutId: this.info.uuid,
        cameraInfo: {},
        replay: {},
        time: 0
      }
      _info.cameraInfo[this.treeNodeKey] = ''
      this.setCameraInfo(_info)
    },
    // 仅关掉播放器
    closePlayer() {
      this.$refs['player'].$destroy()
    },
    getSmartList() {
      this.smartList = this.layoutConfig.smartList.filter(item => {
        return item.cameraId === this.info.cameraInfo[this.treeNodeKey]
      })
    }
  }
}
</script>

<style scoped lang="scss">
.player-main {
  position: absolute;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  overflow: hidden;

  .label-message {
    width: 100%;
    height: auto;
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    text-align: center;
    color: red;
  }

  .player-top-bar {
    position: absolute;
    left: 0;
    top: -30px;
    z-index: 999;
  }

  .player-bottom-bar {
    position: absolute;
    left: 0;
    bottom: -30px;
    z-index: 999;
  }

  &.active .player-top-bar {
    top: 0;
  }

  &.active .player-bottom-bar {
    bottom: 0;
  }

  .player-box {
    width: 100%;
    height: 100%;
    position: relative;
    text-align: center;
    vertical-align: middle;

    video {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }
}
</style>
